//
//  HMComposeViewController.swift
//  01-SinaWeibo
//
//  Created by 周英培 on 16/5/28.
//  Copyright © 2016年 周英培. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
/*
 懒加载不能放在分类里面
 */
/*
 问题一：make.top.equalTo(self.view).offset(64)  在让textview成为第一响应着之前 用的这个约束 才能显示正常 用make.top.equalTo(self.view)会跑到导航条下面 让textview成为第一响应着后 用make.top.equalTo(self.view).offset(64)  占位文字位置变化 还有下面toolbar不显示 并且 第一次不点击command ＋ k时，设置的第一响应着就没用 就不出来 只有点击过一次之后 以后才会正常 还有 toolbar 有时候正常 有时候不正常显示 还有就是点击关闭按钮时 下面的键盘退出的有问题
 问题二：我的微博发布成功时 为什么提示的是个X呢 为啥不是对号呢
 问题三：statuses/upload	上传图片并发布一条微博
 statuses/upload_url_text	发布一条微博同时指定上传的图片或图片url   这两个有啥区别？？？
 */
class HMComposeViewController: UIViewController {
    
    //关闭按钮的响应事件
    @objc private func close() {
        
        dismissViewControllerAnimated(true) {
            
        }
        
    }
    
    //发送按钮的响应事件
    @objc private func send() {
        
        print("发送")
        
        HMNetworkTools.sharedTools.sendStatus(textView.fullText(), images: pictureSelector.images) { (responseObject, error) in
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                print(error)
                
            } else {
                
                SVProgressHUD.showErrorWithStatus("发布微博成功")
                
            }

        }
        
    }

    //选择图片
    @objc private func selectPicture() {
    
        print("选择图片")
        //点击选择图片 图片选择器的view显示在界面上 则更新图片选择器的view
        pictureSelector.view.snp_updateConstraints { (make) in
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
    
    }
    
    //选择表情
    @objc private func selectEmoticon() {
    
        print("选择表情")
        
        //键盘进行切换  系统键盘和自定义键盘的切换
//        textView.inputView = keyboardView
        
        //点击表情键盘还是不能切换 因为系统键盘第一响应着还存在 所以 辞去第一响应着 设置自定义键盘 成为第一响应着 用下面一句代码就可以搞定
        //当是系统键盘时 inputview为nil
        //判断 进行 系统键盘和自定义键盘的来回切换
        textView.inputView = (textView.inputView == nil) ? keyboardView : nil
        textView.reloadInputViews()
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
         setUpUI()
        registerNotification()
        
        //让textview成为第一响应者
//        textView.becomeFirstResponder()
    }
    
    //让键盘显示 在界面显示之后 弹出键盘
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if pictureSelector.images.count == 0 {
            
            textView.becomeFirstResponder()
        }
    }
    
    //MARK:注册通知 
    private func registerNotification() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //注册表情通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(insertEmoticon(_:)), name: EmoticonBtnDidClickNotification, object: nil)
    
    }
    
    //插入表情的通知
    @objc private func insertEmoticon(n:NSNotification) {
        
        guard let em = n.object as? HMEmoticon else {
            
            return
            
        }
        
        //插入点击表情按钮对应的文字
        textView.insertEmoticon(em)
        
    }

    
    //键盘显示出来的时候 toolbar在键盘的上面
    @objc private func keyboardChange(n:NSNotification) {
        //键盘所有的信息都在n里面 包括时间 frame等等
        //获取键盘显示或者隐藏起来的时间
        let time = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //获取键盘显示出来时候的frame 结构体不能直接存放在字典里面 需要转化为NSValue才能存储
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //获取键盘显示出来 自定义的toolbar在键盘上面的位置的Y值
        let offsetY = -ScreenHeight + rect.origin.y
        
        UIView.animateWithDuration(time) { 
            //更改约束
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offsetY)
            })
            
            //刷新界面
            self.view.layoutIfNeeded()
        }
      
    }
    
    //移除通知
    deinit {
    
         NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    
    
    //MARK:懒加载各个子控件
    //工具条
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    //占位符
    private lazy var placeHolderLabel : UILabel = UILabel(title: "哎哟 不错额", font: 14, textColor: UIColor.darkGrayColor())
    
    //添加图片选择器的控制器的属性 方便调用
    private lazy var pictureSelector : HMPictureSelectorController = HMPictureSelectorController()
    
    private lazy var keyboardView: HMEmoticonKeyboardView = HMEmoticonKeyboardView()
    
    //懒加载文本输入视图 不是文本输入框  UITextView 继承自UIScrollView
    private lazy var textView : HMTextView = {
    
    let tv = HMTextView()
    
        tv.backgroundColor = UIColor(white: 0.9, alpha: 1)
//        tv.text = "哎哟 不错额"
        tv.font = UIFont.systemFontOfSize(16)
        tv.textColor = UIColor.darkGrayColor()
        //设置键盘消失的方式  滚动视图时键盘消失
        tv.keyboardDismissMode = .OnDrag
        //设置文本输入视图垂直滚动
        tv.alwaysBounceVertical = true
        
        //设置代理
        tv.delegate = self
        
        return tv
    
    }()
    
    //懒加载导航条右边的发送按钮
    private lazy var rightBarButonItem : UIBarButtonItem = {
    
        let btn = UIButton()
        
        //设置文案 文字颜色 文字大小
        btn.setTitle("发送", forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        //设置不同状态下的背景图片
        btn.setBackgroundImage(UIImage(named:"common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), forState: .Highlighted)
        
        //设置frame
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        
        //给按钮添加点击事件
        btn.addTarget(self, action: #selector(send), forControlEvents: .TouchUpInside)
        
        //设置成导航条的右边barbuttonitem
        let rightBarButtonItem = UIBarButtonItem(customView: btn)
        
        return rightBarButtonItem
    
    }()
    
    
    
}



//设置UI
extension HMComposeViewController {

    private func setUpUI() {
        setToolBar()
        setTextView()
        setNavBar()
        setSelectorVC()
    
    }
    
    //设置底部工具条
    private func setToolBar() {
    
    self.view.addSubview(toolBar)
        
      toolBar.snp_makeConstraints { (make) in
        make.left.right.bottom.equalTo(self.view)
        //工具条有默认高度  49  不用设置高度
        }
        
        //工具条按钮
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        
        for item in itemSettings {
            
            let imageName = item["imageName"]
            let action = item["actionName"]
            
            //添加自定义的UIBarButtonItem
            let item = UIBarButtonItem(imageName: imageName, title: nil, target: self, action: Selector(action!))
            items.append(item)
            
            //给按钮添加弹簧 让他们自动分开
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
            items.append(space)
          
        }
        
        items.removeLast()
        toolBar.items = items
    
    }
    
    //设置文本输入视图
    private func setTextView() {
    
        self.view.addSubview(textView)

        textView.snp_makeConstraints { (make) in
            make.left.right.equalTo(self.view)
//            make.top.equalTo(self.view).offset(64)
            make.top.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(textView).offset(5)
            make.top.equalTo(textView).offset(margin)
        }
    }
    
    //设置导航条上的标题视图 和左右两边的按钮
    private func setNavBar() {
    
        //添加左边的关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "关闭", target: self, action: #selector(close))
        
        //添加右边的发送按钮
        navigationItem.rightBarButtonItem = rightBarButonItem
        
        //设置右边的按钮初始时不能交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置导航条自定义标题视图
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        let titleLabel = UILabel(title: "发布微博", font: 16, textColor: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: HMUserInfoViewModel.sharedUserInfoViewModel.userInfoModel?.name ?? "", font: 14, textColor: UIColor.lightGrayColor())
        
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) in
            make.top.equalTo(myView)
            make.centerX.equalTo(myView)
        }
        nameLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(myView)
            make.bottom.equalTo(myView)
        }
        
       //赋值给导航条的标题视图
        navigationItem.titleView = myView
    
    }
    
    //设置图片选择器的view
    private func setSelectorVC() {
    
        //在添加view之前 先加上图片选择器的属性控制器
        self.addChildViewController(pictureSelector)
        
        //在发布微博控制器的界面上加上图片选择器的view
        self.view.addSubview(pictureSelector.view)
        
        //将toolbar移到最前面  就是点击选择图片时，图片选择器的view显示出来的时候 toolbar要显示在最上面
        self.view.bringSubviewToFront(toolBar)
        
        //设置约束
        pictureSelector.view.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    
    }

}

//遵守协议 输入文字时，占位文字消失 发送按钮可以交互
extension HMComposeViewController : UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        rightBarButonItem.enabled = textView.hasText()
        
        
    }

}
